package cn.com.jinhao.hotline.commons.controller;

import cn.com.jinhao.hotline.commons.base.constant.SystemConstant;
import cn.com.jinhao.hotline.commons.exception.BusinessErrorException;
import cn.com.jinhao.hotline.commons.util.RestResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;


import java.util.List;
import java.util.Optional;

/**
 * 控制器基类
 *
 * @author ShaneWei
 */
public abstract class BaseController {

    /**
     * 接口输入参数合法性校验
     *
     * @param result 参数
     */
    protected void validate(BindingResult result) {
        if (result.hasFieldErrors()) {
            List<FieldError> errorList = result.getFieldErrors();
            errorList.forEach(item -> Assert.isTrue(false, item.getDefaultMessage()));
        }
    }

    protected RestResponse<Object> checkExist(Object obj) {
        if (Optional.ofNullable(obj).isPresent()) {
            return new RestResponse<>(obj);
        } else {
            return new RestResponse<>(SystemConstant.ResponseCode.DATA_NOT_EXIST,null);
        }
    }

    @ExceptionHandler
    public RestResponse<String> doError(Exception e) {
        return StringUtils.isBlank(e.getMessage())?new RestResponse<>(SystemConstant.ResponseCode.FAILED,null):new RestResponse<>(SystemConstant.ResponseCode.SERVER_EXCEPTION,null, e.getMessage());
    }

    @ExceptionHandler(BusinessErrorException.class)
    public RestResponse<String> handlerBusinessErrorException(BusinessErrorException e){
        return StringUtils.isBlank(e.getMessage())?new RestResponse<>(SystemConstant.ResponseCode.BUSINESS_EXCEPTION, null):new RestResponse<>(SystemConstant.ResponseCode.BUSINESS_EXCEPTION, null, e.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public RestResponse<String> handlerIllegalStateException(IllegalArgumentException e) {
        return StringUtils.isBlank(e.getMessage())?new RestResponse<>(SystemConstant.ResponseCode.VALIDATION_ERROR, null):new RestResponse<>(SystemConstant.ResponseCode.VALIDATION_ERROR, null, e.getMessage());
    }
}
